import {Component, OnInit} from '@angular/core';
import {AliyunOssOutputUrl} from '../../../../../config/api';
import {ActivatedRoute, Router} from '@angular/router';
import {isInteger} from '@ng-bootstrap/ng-bootstrap/util/util';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import * as moment from 'moment';
import {GroupService} from '../../group.service';
import {NzMessageService} from 'ng-zorro-antd';
import {observable} from "rxjs/symbol/observable";

@Component({
  selector: 'app-edit-lottery',
  templateUrl: './edit-lottery.component.html',
  styleUrls: ['./edit-lottery.component.scss'],
  providers: [GroupService]
})
export class EditLotteryComponent implements OnInit {

  aliyunOssOutputUrl = AliyunOssOutputUrl;
  validateForm: FormGroup;
  _isSpinning = false;
  start_date = null;
  end_date = null;
  prize = [{class: '一等奖', level: 1, sku: [], type: null, checkedSkuId: null, error: {goods: false, number: false}}];
  operatePrizeIndex;  // 当前正在操作的奖品等级
  activity_goods_prize;
  stage; // 团进行状态 1-未开始 2-进行中 3-已结束

  /* 商品弹窗 */
  goodsModalVisible = false;
  goodsList = [];
  groupList = [];
  selectedGroup;
  keyword;
  currentClickGoods = {};
  page = 1;
  pageSize = 5;
  total;
  queryParams: any;
  loading = false;
  status = '上架';
  isNewGroup = false;
  currentGoodsPrice = 0;
  disabledNewGroup = false;

  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  }
  _startValueChange = () => {
    if (this.start_date > this.end_date) {
      this.end_date = null;
    }
  }
  _endValueChange = () => {
    if (this.start_date > this.end_date) {
      this.start_date = null;
    }
  }
  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!startValue || !this.validateForm.value.validity_end) {
      return startValue < now_time;
    }
    return (startValue.getTime() >= this.validateForm.value.validity_end.getTime()) || (startValue.getTime() <= Date.now());
  }
  _disabledEndDate = (endValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!endValue || !this.start_date) {
      return endValue.getTime() < now_time;
    }
    return endValue.getTime() < this.start_date.getTime();
  }

  get _isSameDay() {
    return this.start_date && this.end_date && moment(this.start_date).isSame(this.end_date, 'day');
  }

  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this.start_date.getHours()) : [];
      },
      nzDisabledMinutes: (h) => {
        if (this._isSameDay && h === this.start_date.getHours()) {
          return this.newArray(this.start_date.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (this._isSameDay && h === this.start_date.getHours() && m === this.start_date.getMinutes()) {
          return this.newArray(this.start_date.getSeconds());
        }
        return [];
      }
    };
  }

  // 整数验证
  integerValidators = (control: FormControl): { [s: string]: boolean } => {
    return Observable.create(function (observer) {
      if (!isInteger(control.value)) {
        observer.next({error: true, notInteger: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  }

  //价格验证
  priceValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value > this.currentGoodsPrice) {
        observer.next({error: true, priceToHigh: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    })
  };
  //
  // CountValidators = (control: FormControl) => {
  //   return observable.create((observer) => {
  //
  //   })
  // }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  constructor(private fb: FormBuilder,
              private groupService: GroupService,
              private route: ActivatedRoute,
              private router: Router,
              private _message: NzMessageService,
  ) {
    this.validateForm = this.fb.group({
      group_type: [3, [Validators.required]],
      id: [null, [Validators.required]],
      activity_goods_id: [null, Validators.required],
      number: [null, [Validators.required, Validators.min(2), Validators.max(20)], [this.integerValidators]],
      new_offer: [false, [Validators.required]],
      price: ['', [Validators.required, Validators.min(0.01), Validators.max(99999999)]],
      start_date: [null, [Validators.required]],
      end_date: [null, [Validators.required]],
      name: ['', [Validators.required, Validators.maxLength(30)]],
      min_awards: [null, [Validators.min(0), Validators.max(999)], [this.integerValidators]],  // 开奖团数
      round: [null, [Validators.required, Validators.min(0), Validators.max(999)]],  // 单人参与次数
      is_show: [1, [Validators.required]],
      sorts: [null, [Validators.required, Validators.min(0), Validators.max(99)], [this.integerValidators]]
    });
  }

  ngOnInit() {
    const id = +this.route.snapshot.params['id'];
    this.validateForm.controls['id'].setValue(id);
    this.getGroupInfo(id);
    this.getGroupList();
  }

  // 搜索商品
  searchGoods() {
    this.page = 1;
    this.getGoodsList();
  }


  // 获取拼团详情
  getGroupInfo(id) {
    this.groupService.getActivityInfo(id).subscribe(res => {
      if (res.code === 2000) {
        const data = res.data;
        this.stage = data.stage;
        let nowTime = new Date().getTime();
        if (nowTime > new Date(data.start_date).getTime()) {
          this.disabledNewGroup = true;
        }
        const startDate = new Date(data.start_date + ' 00:00:00');
        const endDate = new Date(data.end_date + ' 23:59:59');
        this.validateForm.controls['activity_goods_id'].setValue(data.activity_goods_id);
        this.validateForm.controls['group_type'].setValue(data.group_type);
        this.validateForm.controls['name'].setValue(data.name);
        this.validateForm.controls['min_awards'].setValue(data.min_awards);
        this.validateForm.controls['number'].setValue(data.number);
        this.validateForm.controls['price'].setValue(data.activity_goods.price / 1000);
        this.validateForm.controls['round'].setValue(data.round);
        this.validateForm.controls['start_date'].setValue(startDate);
        this.validateForm.controls['end_date'].setValue(endDate);
        this.validateForm.controls['new_offer'].setValue(data.new_offer ? true : false);
        this.validateForm.controls['sorts'].setValue(data.sorts);
        const prize = [];
        data.activity_goods_prize.every((val, idx, array) => {
          let prize_item;
          switch (val.level) {
            case 1:
              prize_item = {
                class: '一等奖',
                level: 1,
                goods: {},
                sku: [],
                checkedSkuId: null,
                error: {goods: false, number: false, toHigh: false}
              };
              break;
            case 2:
              prize_item = {
                class: '二等奖',
                level: 2,
                goods: {},
                sku: [],
                checkedSkuId: null,
                error: {goods: false, number: false, toHigh: false}
              };
              break;
            case 3:
              prize_item = {
                class: '三等奖',
                level: 3,
                goods: {},
                sku: [],
                checkedSkuId: null,
                error: {goods: false, number: false, toHigh: false}
              };
              break;
            case 4:
              prize_item = {
                class: '四等奖',
                level: 4,
                goods: {},
                sku: [],
                checkedSkuId: null,
                error: {goods: false, number: false, toHigh: false}
              };
              break;
            case 5:
              prize_item = {
                class: '五等奖',
                level: 5,
                goods: {},
                sku: [],
                checkedSkuId: null,
                error: {goods: false, number: false, toHigh: false}
              };
              break;
          }
          prize_item['type'] = val.type;
          prize_item['level'] = val.level;
          prize_item['number'] = val.number;
          prize_item.goods['name'] = val.prize_name;
          prize_item.goods['first_picture'] = val.prize_pic;
          prize_item.goods['id'] = val['goods_id'];
          this.groupService.getGoodsSkuList(val['goods_id'], 100).subscribe(res => {
            if (res.code === 2000) {
              const sku = res.data.data;
              prize_item['checkedSkuId'] = JSON.parse(val.prize_info).id;
              prize_item['sku'] = sku;
              prize_item['sku'].forEach((e, i) => {
                if (e.id == prize_item['checkedSkuId']) {
                  let skuPrice = e.price / 1000;
                  if (skuPrice > this.currentGoodsPrice) {
                    this.currentGoodsPrice = skuPrice;
                  }
                  prize_item['in_stock'] = e.in_stock;
                }
                let value = parseFloat(this.validateForm.get('price').value);
                this.validateForm.removeControl('price');
                this.validateForm.addControl('price', this.fb.control(value, [Validators.required, Validators.min(0.01), Validators.max(99999999)], [this.priceValidators]));
              });
            } else {
              this._message.create('error', res.message);
            }
          });
          this.groupService.getbindListAll(val.goods_id).subscribe(rs => {
            if (rs.code === 2000) {
              prize_item.goods['goods_category'] = rs.data;
            } else {
              this._message.create('error', rs.message);
            }
          });
          prize.push(prize_item);
          return true;
        });
        this.prize = prize;
      }
    });
  }


  // 获取店铺商品类型列表
  getGroupList() {
    this.groupService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
    });
  }

  goBack() {
    this.route.queryParams.subscribe(queryParams => {
      this.queryParams = queryParams;
    });
    this.router.navigate(['/member/group/list'], {
        queryParams: this.queryParams,
        relativeTo: this.route
      }
    );
  }

  changeSku(i, sku) {
    console.log(this.prize[i]);
  }

  reset() {
    this.selectedGroup = null;
    this.keyword = '';
    this.page = 1;
    this.getGoodsList();
  }

  // 获取商品列表
  getGoodsList() {
    this.loading = true;
    this.groupService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.keyword, this.status).subscribe(res => {
      if (res.code === 2000) {
        this.total = res.data.total;
        const goodsList = res.data.data;
        const goodsId = [];
        goodsList.forEach(item => {
          goodsId.push(item.id);
        });
        this.groupService.getbindListAll('[' + goodsId.join(',') + ']').subscribe(rs => {
          if (rs.code === 2000) {
            const goodsjson = {};
            rs.data.forEach(item => {
              if (!goodsjson[item.goods_id]) {
                goodsjson[item.goods_id] = [item.name];
              } else {
                goodsjson[item.goods_id].push(item.name);
              }
            });
            goodsList.forEach(item => {
              if (item.goods_number) {
                item.goods_number = item.goods_number.split('|');
              }
              item.goods_category = goodsjson[item.id];
            });
          }
          if (this.prize[this.operatePrizeIndex].hasOwnProperty('goods')) {
            goodsList.forEach((e, i) => {
              if (e.id === this.prize[this.operatePrizeIndex]['goods']['id']) {
                this.prize[this.operatePrizeIndex]['currentClickGoods'] = e;
              }
            });
          }
          this.goodsList = goodsList;
          this.loading = false;
        });
      } else {
        this._message.create('error', res.message);
      }
      this.loading = false;
    });
  }

  saveClickGoods(data, flag?) {
    if (flag) {
      return data;
    } else {
      this.prize[this.operatePrizeIndex]['currentClickGoods'] = data;
    }
  }

  addPrize(idx) {
    this.operatePrizeIndex = idx;
    if (!this.prize[this.operatePrizeIndex].hasOwnProperty('currentClickGoods')) {
      this.prize[this.operatePrizeIndex]['currentClickGoods'] = {};
    }
    this.page = 1;
    this.getGoodsList();
    this.goodsModalVisible = true;
  }


  checkedStock(i, current) {
    let item = this.prize[i];
    item['in_stock'] = current;
    if (item['number'] > item['in_stock']) {
      item['error']['toHigh'] = true;
    } else {
      item['error']['toHigh'] = false;
    }
  }

  checkCount(e, i) {
    if (!parseInt(e)) {
      this.prize[i].error['number'] = true;
    } else {
      this.prize[i].error['number'] = false;
      if (this.prize[i]['in_stock'] < e) {
        this.prize[i].error['toHigh'] = true;
      } else {
        this.prize[i].error['toHigh'] = false;
      }
    }
  }


  // 增加奖项
  addAwards() {
    const len = this.prize.length;
    let prize_item;
    switch (len) {
      case 1:
        prize_item = {class: '二等奖', level: 2, sku: [], checkedSkuId: null, error: {}};
        break;
      case 2:
        prize_item = {class: '三等奖', level: 3, sku: [], checkedSkuId: null, error: {}};
        break;
      case 3:
        prize_item = {class: '四等奖', level: 4, sku: [], checkedSkuId: null, error: {}};
        break;
      case 4:
        prize_item = {class: '五等奖', level: 5, sku: [], checkedSkuId: null, error: {}};
        break;
      case 5:
        return;
    }
    this.prize.push(prize_item);
  }

  confirmCheckedGoods() {
    if (!Object.keys(this.prize[this.operatePrizeIndex]['currentClickGoods']).length) {
      this._message.create('error', '请选择商品');
      return;
    }
    ;
    this.prize[this.operatePrizeIndex]['goods'] = JSON.parse(JSON.stringify(this.prize[this.operatePrizeIndex]['currentClickGoods']));
    this.prize[this.operatePrizeIndex]['type'] = 1;
    // 获取选择商品的sku
    this.groupService.getGoodsSkuList(this.prize[this.operatePrizeIndex]['currentClickGoods']['id'], 100).subscribe(res => {
      if (res.code === 2000) {
        const sku = res.data.data;
        if (this.prize[this.operatePrizeIndex]['checkedSkuId'] != sku[0].id) {
          this.prize[this.operatePrizeIndex]['sku'] = sku;
          this.prize[this.operatePrizeIndex]['checkedSkuId'] = sku[0].id;
          this.prize[this.operatePrizeIndex]['in_stock'] = sku[0].in_stock;
        }
        this.goodsModalVisible = false;
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  // 删除奖项
  deletePrize(idx) {
    const len = this.prize.length;
    this.prize.splice(idx, 1);
    if (idx < len - 1) {
      this.prize.every((val, idx, array) => {
        val.level = idx + 1;
        switch (idx) {
          case 1:
            val.class = '二等奖';
            break;
          case 2:
            val.class = '三等奖';
            break;
          case 3:
            val.class = '四等奖';
            break;
          case 4:
            val.class = '五等奖';
            break;
        }
        return true;
      });
    }
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    // 验证是否选择sku
    const activity_goods_prize = [];
    let passValidation = true;
    this.prize.every((val, idx, array) => {
      if (!val.checkedSkuId) {
        val.error['goods'] = true;
        passValidation = false;
      } else {
        val.error['goods'] = false;
      }
      if (!val['number']) {
        val.error['number'] = true;
        passValidation = false;
      } else {
        val.error['number'] = false;
      }
      const price_item = {level: val.level, type: val.type, id: val.checkedSkuId, number: val['number']};
      activity_goods_prize.push(price_item);
      return true;
    });
    this.activity_goods_prize = activity_goods_prize;
    if (this.validateForm.valid && passValidation) {
      this.validateForm.value['activity_goods_prize'] = JSON.stringify(this.activity_goods_prize);
      this.validateForm.value['start_date'] = moment(this.validateForm.value.start_date).format('YYYY-MM-DD');
      this.validateForm.value['end_date'] = moment(this.validateForm.value.end_date).format('YYYY-MM-DD');
      this.validateForm.value['new_offer'] = this.validateForm.value['new_offer'] ? 1 : 0;
      this._isSpinning = true;
      this.groupService.postEditGroup(this.validateForm.value).subscribe(res => {
        if (res.code === 2000) {
          const nowTime = new Date().getTime();
          const startTime = new Date(this.validateForm.value['start_date']).getTime();
          this._message.create('success', '修改拼团成功');
          this.route.queryParams.subscribe(queryParams => {
            this.queryParams = queryParams;
          });
          let stage = nowTime < startTime ? 1 : 2;
          this.router.navigate(['/member/group/list'], {
            queryParams: {
              type: this.queryParams.type,
              stage: stage
            },
            relativeTo: this.route
          });
          // if(nowTime < startTime) {
          //   this.router.navigate(['/member/group/list'],{
          //       queryParams: {
          //         type:this.queryParams.type,
          //         stage: 1
          //       },
          //       relativeTo: this.route
          //     }
          //   );
          // } else {
          //   this.router.navigate(['/member/group/list'],{
          //       queryParams: {
          //         type:this.queryParams.type,
          //         stage: 2
          //       },
          //       relativeTo: this.route
          //     }
          //   );
          // }
          // this.router.navigate(['/member/group/list'],{
          //   queryParams: this.queryParams,
          //   relativeTo: this.route
          // }
          // );
        } else {
          this._message.create('error', res.message);
        }
        this._isSpinning = false;
      });
    }
  }
}
